<?php

namespace app\agent\controller;

use app\common\controller\Adminbase;
use app\job\UpdateGoodsSharePrice;
use app\model\AdminAgent;
use app\model\AgentDistribution;
use app\model\DistributionSetting;
use app\service\AgentService;
use think\Queue;

class Distribution extends Adminbase
{

    public function form()
    {
        $agent = AgentService::getAgentInfo(UID);
        $info  = AgentDistribution::where('agent_id', $agent['id'])->find();
        $value = DistributionSetting::where('uuid', 'setting')->value('value');
        if (empty($info)) {
            $info = [
                'agent_id' => $agent['id'],
                'type'     => 0,
                'value'    => $value,
            ];
            AgentDistribution::create($info);
            $info['level'] = json_decode($value, true);
        } else {
            $info['level'] = json_decode($info['value'], true);
        }
        $is_update = true;
        //如果代理商不能自定义分销设置，则使用系统默认设置
        if (!in_array(AdminAgent::RULE_CUSTOM_RATIO, $agent['rules'])) {
            $is_update     = false;
            $info['level'] = json_decode($value, true);
        }
        $ratio = $info['level'][0]['ratio'] ?? 0;
        if ($this->request->isPost()) {
            $data           = $this->request->post();
            $data['income'] = $data['income'] > 0 ? ($data['income'] * 100) : 0;
            $data['value']  = json_encode($data['level'], JSON_UNESCAPED_UNICODE);

            unset($data['level']);
            AgentDistribution::where('agent_id', $agent['id'])->update($data);
            return json(['code' => 0, 'msg' => '操作成功']);
        }

        $type = [
            0 => '关闭',
            1 => '一级',
        ];
        $this->assign([
            'type'           => $type,
            'info'           => $info,
            'invite'         => $info['level']['invite'] ?? 0,
            'income'         => !empty($info['income']) ? ($info['income'] / 100) : 0,
            'task_condition' => $info['task_condition'] ?? 0,
        ]);
        if ($is_update) {
            return $this->fetch('agent/distribution');
        }
        return $this->fetch('agent/distribution_read');
    }

}
